package com.pucheng.bracelet.viewmodel.clock

import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.clj.fastble.exception.BleException
import com.google.gson.Gson
import com.pucheng.bracelet.app.ble.BleCmd
import com.pucheng.bracelet.app.ble.BleWriteAndNotifyCallback
import com.pucheng.bracelet.app.ble.ClientManager
import com.pucheng.bracelet.app.ext.KEY_CLOCK
import com.pucheng.bracelet.app.util.ByteUtils
import com.pucheng.bracelet.app.util.DateFormat
import com.pucheng.bracelet.ui.adapter.ClockData
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import com.pucheng.bracelet.app.util.DatetimeUtil

/**
 * @author liwei
 * @date 2/21/21
 * @email liwei254610320@163.com
 */
class ClockViewModel : BaseViewModel() {
    private var data = mutableListOf<ClockData>().apply {
        add(ClockData(0, "8:00", 0, false))
        add(ClockData(1, "2:00", 0, false))
        add(ClockData(2, "9:00", 0, false))
    }

    private val itemsAP: MutableList<String> = mutableListOf<String>().apply {
        add("上午")
        add("下午")
    }

    private val itemsHour: MutableList<String> = mutableListOf<String>().apply {
        for (i in 1..12) {
            add("$i")
        }
    }

    private val itemsMinute: MutableList<String> = mutableListOf<String>().apply {
        for (i in 0..59) {
            if (i < 10) {
                add("0$i")
            } else {
                add("$i")
            }
        }
    }

    var clockData = MutableLiveData<MutableList<ClockData>>().apply {
        var string = SPUtils.getInstance().getString(KEY_CLOCK)
        if (string.isNotEmpty()) {
            val push = Gson().fromJson(string, Clock::class.java)
            if (push?.data != null) {
                data.clear()
                data.addAll(push.data)
            }
        }
        value = data
    }

    var timeClock = MutableLiveData<MutableList<Int>>().apply {
        value = mutableListOf<Int>().apply {
            add(0)
            add(0)
            add(0)
        }
    }
    var timeAp = MutableLiveData<MutableList<String>>().apply {
        value = itemsAP
    }
    var timeHour = MutableLiveData<MutableList<String>>().apply {
        value = itemsHour
    }
    var timeMinute = MutableLiveData<MutableList<String>>().apply {
        value = itemsMinute
    }

    var weekRepeatState = MutableLiveData<Int>().apply { value = 0 }
    var weekRepeatStr = MutableLiveData<String>()
    var editClockDataIndex = MutableLiveData<Int>()
    var editClockData = MutableLiveData<ClockData>()
    private var editClock: ClockData? = null
    var mApIndex = MutableLiveData<Int>().apply { value = 0 }
    var mHourIndex = MutableLiveData<Int>().apply { value = 0 }
    var mMinuteIndex = MutableLiveData<Int>().apply { value = 0 }

    fun selectData(index: Int, clockData: ClockData) {
        if (data.size > index) {
            data[index] = clockData
            SPUtils.getInstance().put(
                KEY_CLOCK, Gson().toJson(
                    Clock(
                        data
                    )
                )
            )
        }

    }

    /**
     * 保存闹钟
     */
    fun saveClock() {
        changeTime()
        editClock?.apply {
            selectData(editClockDataIndex.value!!, this)
            editClockData.value = this
            clockData.value = data
        }
    }

    /**
     * 设置时间
     */
    fun changeTime() {
        val hour = if (mApIndex.value!!.toInt() == 0) {
            itemsHour[mHourIndex.value!!.toInt()]
        } else {
            itemsHour[mHourIndex.value!!.toInt()].toInt() + 12
        }
        val minute = itemsMinute[mMinuteIndex.value!!.toInt()]
        editClock = editClockData.value?.apply {
            clockTime = "$hour:$minute"
            weekRepeat = weekRepeatState.value!!.toInt()
        }

    }

    /**
     * 初始化
     */
    fun initTime(clockDataIndex: Int?, clockData: ClockData?) {
        editClockDataIndex.value = clockDataIndex
        editClockData.value = clockData
        clockData?.apply {
            val clockTimeStr = DateFormat.timeFormat(clockTime)
            val strs = clockTimeStr.split(" ")
            val ap = strs[0]
            val time = strs[1].split(":")
            mApIndex.value = itemsAP.indexOf(ap)
            mHourIndex.value = if (time[0].trim().toInt()>12){
                time[0].trim().toInt() -13
            }else{
                time[0].trim().toInt()-1
            }
            mMinuteIndex.value =time[1].trim().toInt()

//            changeTime()
        }
    }

    /**
     * 获取重复日期
     */
    fun getWeekRepeatData(weekRepeat: Int) {
        weekRepeatState.value = weekRepeat
        weekRepeatStr.value = DatetimeUtil.getWeekRepeatData(weekRepeat)
    }

    /**
     * 同步闹钟到手环
     */
    fun setClockDataToBle() {
        ClientManager.getInstance().sendControlCmd(getClockCmd(),object: BleWriteAndNotifyCallback(){
            override fun onCharacteristicChanged(data: ByteArray?) {

            }

            override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
            }

            override fun onWriteFailure(exception: BleException?) {

            }
        })
    }

    /**
     * 获取闹钟指令
     */
    fun getClockCmd():String{
        val clockStr = StringBuffer(BleCmd.SYNC_CLOCK)
        val list = clockData.value
        for (clockData in list!!) {
            clockStr.append("0${if (clockData.selected){1}else 0}")
            clockStr.append(ByteUtils.intToHex16(clockData.weekRepeat))
            val hour = clockData.clockTime.split(":")[0].trim().toInt()
            clockStr.append(ByteUtils.intToHexByLength(hour,1))
            clockStr.append(ByteUtils.intToHexByLength(clockData.clockTime.split(":")[1].trim().toInt(),1))
        }
        LogUtils.e("闹钟指令：$clockStr")
        return clockStr.toString()
    }

}

data class Clock(val data: List<ClockData>?)